package com.yc.demohoudun.web;

import com.yc.demohoudun.entiy.*;
import com.yc.demohoudun.mapper.ProductMapper;
import com.yc.demohoudun.service.ProductService;
import com.yc.demohoudun.service.ServiceException;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.yc.demohoudun.web.UserAction.usernewName;

@RestController
@RequestMapping("product")
public class ProductController {
    @Autowired
    ProductMapper productMapper;
    @Autowired
    ProductService productService;


    @GetMapping("/news")
    Page queryNews(Page page, String name,
                     @RequestParam(defaultValue ="0") int price1,
                     @RequestParam(defaultValue ="0") int price2,
                   @RequestParam(required = false) String category) {
        int begin=(page.getPage()-1)* page.getSize();
        if (name.isBlank())name=null;
        List<Product> products = productMapper.selectByNameAndPrice(name, price1, price2, begin, page.getSize(),category);
        int total = productMapper.countByNameAndPrice(name, price1, price2);
        page.setData(products);
        page.setTotal(total);
        return page;
    }

    @RequestMapping("/save")
    public Result save(@RequestBody Product product) {
        try {

            productService.save(product);
            return new Result(1,"保存商品成功",product);
        } catch (ServiceException e) {
            return new Result(1,e.getMessage(),null);
        }

    }
    @GetMapping("/select/{name}")
    public Result selectByname(@PathVariable String name) {

        return productService.selectByname(name);
    }

    @GetMapping("/del")
    public Result remove(int id) {

        productMapper.deleteById(id);
        return new Result(1,"删除商品成功",null);
    }

    @GetMapping("/detail")
    public Result productDetail(int id) {

        return  productService.selectDetail(id);
    }
    @GetMapping("/score/{id}")
    public Result score(@PathVariable int id) {

        return productService.selectProductscore(id);
    }

    @PostMapping("/inscore")
    public Result inScore(@RequestBody  Score score) {
        String username=usernewName;

       Score score1 = new Score();
       score1.setScore(score.getScore());
       score1.setComment(score.getComment());
       score1.setProductId(score.getId());
       score1.setPerson(usernewName);

        return  productService.inscore(score1);
    }


}
